package com.hhq.sso.protocol.oauth2.filter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * <p>Description: 图形验证码过滤器 </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/19 11:17
 */
public class CaptchaAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private String defaultFilterProcessesUrl = "/login";
    private String captchaSessionKey;

    public CaptchaAuthenticationFilter(String defaultFilterProcessesUrl, String captchaSessionKey) {
        this.captchaSessionKey = captchaSessionKey;
        setFilterProcessesUrl(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        String captcha = request.getParameter("captcha");
        HttpSession session = request.getSession();

        if (captcha == null || captcha.isEmpty()) {
            throw new AuthenticationServiceException("Captcha verification failed");
        }

        String expectedCaptcha = (String) session.getAttribute(captchaSessionKey);
        if (!captcha.equals(expectedCaptcha)) {
            throw new AuthenticationServiceException("Invalid Captcha");
        }
        return super.attemptAuthentication(request, response);
    }
}
